package com.xdap.common.util;

import com.xdap.common.constant.TokenConstant;
import com.xdap.common.consts.ComConst;
import com.xdap.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ComApaasTokenUtil {

    @Value("${apaas.single.appId}")
    private String appId;
    @Value("${apaas.single.tenantId}")
    private String tenantId;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
    *@auth lishushu
    *@2024/3/18 16:18
    *@desc {获取可以调用平台后端的token}
    **/
    public String getToken() {
        String key = tenantId +"" +appId + "-apaasToken-tk";
        String apaasToken = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(apaasToken)) {
            apaasToken = this.getApaasToken();
            stringRedisTemplate.opsForValue().set(key, apaasToken, 30, TimeUnit.MINUTES);
        }
        return apaasToken;

    }


    public HttpHeaders dealApaasHeaders() {
        // 获取apaas Token
        String apaasToken = getApaasToken();
        // 封装请求头信息。
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json;charset=utf-8");
        httpHeaders.add("Accept", "application/json;charset=utf-8");
        httpHeaders.add(ComConst.XDAPTENANTID, tenantId);
        httpHeaders.add(ComConst.XDAPTIMESTAMP, System.currentTimeMillis() + "");
        httpHeaders.add(ComConst.XDAPTOKEN, apaasToken);
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        //     orgHeader.set("Authorization", "Basic " + ComPluginPropertiesUtil.getProperty("ipaas.auth.basic"));

        return httpHeaders;
    }

    private String getApaasToken() {

        /**
         * @param user
         * @param appId
         * @param tenantId
         * @return
         * @DESC 当前页面的token，根据此token可以进入页面
         */
        Map<String, Object> claims = new HashMap<>();
        claims.put(TokenConstant.XDAP_USER_ID, ComConst.XIAO_XUAN);
        claims.put(TokenConstant.XDAP_TENANT_ID, tenantId);
        claims.put(ComConst.XDAPAPPID, appId);
        log.info("XDAP_TENANT_ID:{}", tenantId);
        log.info("xdapappid:{}", appId);

        String token = JwtUtils.createJWT(claims, 60 * 60 * 1000L * 24);
        //  String refreshToken = JwtUtils.createJWT(claims, 10000L);
        this.stringRedisTemplate.opsForValue().set(token, token, 60 * 60 * 1000L * 24,
                TimeUnit.MILLISECONDS);

        return token;
    }

}
